<!DOCTYPE html>
<html>
<head>
    <title>文件管理器</title>
    <link rel="stylesheet" href="/static/style.css">
</head>
<body>
    <div class="container">
        <div class="path-nav">
            <a href="/?path=">根目录</a>
            {% if parent_dir %}
                / <a href="/?path={{ parent_dir }}">上级目录</a>
            {% endif %}
        </div>

        <div class="file-list">
            {% for item in items %}
                <div class="item">
                    {% if item.is_dir %}
                        📁 <a href="/?path={{ current_path }}/{{ item.name }}">{{ item.name }}/</a>
                    {% else %}
                        📄 <a href="#" onclick="loadFile('{{ current_path }}/{{ item.name }}')">{{ item.name }}</a>
                        <span class="size">({{ item.size|filesizeformat }})</span>
                    {% endif %}
                </div>
            {% endfor %}
        </div>

        <div class="editor" id="editor" style="display: none;">
            <h3>编辑文件: <span id="filename"></span></h3>
            <textarea id="content" rows="20"></textarea>
            <button onclick="saveFile()">保存</button>
            <span id="status"></span>
        </div>
    </div>

    <script>
        function loadFile(path) {
            fetch(`/file?path=${encodeURIComponent(path)}`)
                .then(response => response.json())
                .then(data => {
                    document.getElementById('editor').style.display = 'block';
                    document.getElementById('content').value = data.content;
                    document.getElementById('filename').textContent = data.path;
                    document.getElementById('filename').dataset.path = data.path;
                });
        }

        function saveFile() {
            const path = document.getElementById('filename').dataset.path;
            const content = document.getElementById('content').value;

            fetch('/save', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify({
                    path: path,
                    content: content
                })
            })
            .then(response => response.json())
            .then(data => {
                document.getElementById('status').textContent =
                    data.status === 'success' ? '保存成功！' : '保存失败：' + data.message;
                setTimeout(() => {
                    document.getElementById('status').textContent = '';
                }, 3000);
            });
        }
    </script>
</body>
</html>